﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DispatchAssist.BusinessLogical.DAL;
using CarolLib;
using DispatchAssist.BusinessLogical.Model;
using DispatchAssist.Model;

namespace DispatchAssist.BusinessLogical.BLL
{
    public class AuthManager
    {
        #region Members

        private IDataProvider _provider;
        static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private int CacheTime = 3600;
        private readonly static string ALlRoleCacheKey = "ALlRoleCacheKey";
        private readonly static string ALlUserCacheKey = "ALlUserCacheKey";
        private readonly static string ALlSeatCacheKey = "ALlSeatCacheKey";
        private readonly static string ALlSystemModuleCacheKey = "ALlSystemModuleCacheKey";
        private readonly static string ALlSeatMonitorCacheKey = "ALlSeatMonitorCacheKey";
        private readonly static string ALlContactGroupCacheKey = "ALlContactGroupCacheKey";
        private readonly static string ALlContactCacheKey = "ALlContactCacheKey";

        #endregion

        #region Ctor.

        public static readonly AuthManager Instance = new AuthManager();

        public AuthManager()
        {
            _provider = new SqlDataProvider();
        }

        #endregion

        #region CRUD Methods
        public bool DeleteSMSContact(Guid contactID)
        {
            try
            {
                if (_provider.DeleteSMSContact(contactID))
                {
                    CacheHelper.Remove(ALlContactCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. DeleteSMSContact() ", e);
                return false;
            }
        }
        public bool UpdateSMSContact(SMSContact contact)
        {
            try
            {
                if (_provider.UpdateSMSContact(contact))
                {
                    CacheHelper.Remove(ALlContactCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. UpdateSMSContact() ", e);
                return false;
            }
        }
        public bool CreateSMSContact(SMSContact contact)
        {
            try
            {
                if (_provider.CreateSMSContact(contact))
                {
                    CacheHelper.Remove(ALlContactCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. CreateSMSContact() ", e);
                return false;
            }
        }
        public List<SMSContact> GetAllSMSContacts()
        {
            try
            {
                List<SMSContact> list;
                if (!CacheHelper.TryGet<List<SMSContact>>(ALlContactCacheKey, out list))
                {
                    list = _provider.GetAllSMSContacts();
                    CacheHelper.Insert(ALlContactCacheKey, list, CacheTime);
                }
                return list;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. GetAllSMSContacts() ", e);
                return null;
            }
        }
        public List<SMSContactGroup> GetContactGroup()
        {
            try
            {
                List<SMSContactGroup> list;
                if (!CacheHelper.TryGet<List<SMSContactGroup>>(ALlContactGroupCacheKey, out list))
                {
                    list = _provider.GetContactGroup();
                    CacheHelper.Insert(ALlContactGroupCacheKey, list, CacheTime);
                }
                return list;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. GetContactGroup() ", e);
                return null;
            }
        }
        public DispatchAssist.BusinessLogical.Model.Enums.DataAccessReturnValue CreateSMSContactGroup(SMSContactGroup group)
        {
            try
            {
                DispatchAssist.BusinessLogical.Model.Enums.DataAccessReturnValue result = _provider.CreateSMSContactGroup(group);
                if (result == DispatchAssist.BusinessLogical.Model.Enums.DataAccessReturnValue.更新成功)
                {
                    CacheHelper.Remove(ALlContactGroupCacheKey);
                }
                return result;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. CreateSMSContactGroup() ", e);
                return Enums.DataAccessReturnValue.更新失败;
            }
        }
        public DispatchAssist.BusinessLogical.Model.Enums.DataAccessReturnValue UpdateSMSContactGroup(SMSContactGroup group)
        {
            try
            {
                DispatchAssist.BusinessLogical.Model.Enums.DataAccessReturnValue result = _provider.UpdateSMSContactGroup(group);
                if (result == DispatchAssist.BusinessLogical.Model.Enums.DataAccessReturnValue.更新成功)
                {
                    CacheHelper.Remove(ALlContactGroupCacheKey);
                }
                return result;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. UpdateSMSContactGroup() ", e);
                return Enums.DataAccessReturnValue.更新失败;
            }
        }
        public bool DeleteSMSContactGroup(Guid groupID)
        {
            try
            {
                if (_provider.DeleteSMSContactGroup(groupID))
                {
                    CacheHelper.Remove(ALlContactGroupCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. DeleteSMSContactGroup() ", e);
                return false;
            }
        }
        public List<SeatMonitor> GetSeatMonitors()
        {
            try
            {
                //List<SeatMonitor> list;
                //if (!CacheHelper.TryGet<List<SeatMonitor>>(ALlSeatMonitorCacheKey, out list))
                //{
                //    list = _provider.GetSeatMonitors();
                //    CacheHelper.Insert(ALlSeatMonitorCacheKey, list, CacheTime);
                //}
                //return list;

                return CommonCacheData.CacheST.SeatMonitorList;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. GetSeatMonitors() ", e);
                return null;
            }
        }
        public DispatchAssist.BusinessLogical.Model.Enums.DataAccessReturnValue CreateSeatMonitor(SeatMonitor seatMonitor)
        {
            try
            {
                DispatchAssist.BusinessLogical.Model.Enums.DataAccessReturnValue result = _provider.CreateSeatMonitor(seatMonitor);
                if (result == DispatchAssist.BusinessLogical.Model.Enums.DataAccessReturnValue.更新成功)
                {
                    CacheHelper.Remove(ALlSeatMonitorCacheKey);
                }
                return result;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. CreateSeatMonitor() ", e);
                return Enums.DataAccessReturnValue.更新失败;
            }
        }
        public bool DeleteSeatMonitor(Guid seatMonitorID)
        {
            try
            {
                if (_provider.DeleteSeatMonitor(seatMonitorID))
                {
                    CacheHelper.Remove(ALlSeatMonitorCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. DeleteSeatMonitor() ", e);
                return false;
            }
        }
        public List<SeatRole> GetAllSeatRole()
        {
            try
            {
                List<SeatRole> list = CacheHelper.Get<List<SeatRole>>(ALlRoleCacheKey);

                if (list == null)
                {
                    list = _provider.GetAllSeatRole();
                    System.Web.Caching.SqlCacheDependency dependency = new System.Web.Caching.SqlCacheDependency
                       (System.Configuration.ConfigurationManager.AppSettings["CurrentDB"], "SeatRole");

                    CacheHelper.Insert(ALlRoleCacheKey, list, dependency);

                }
                return list;

                //if (!CacheHelper.TryGet<List<SeatRole>>(ALlRoleCacheKey, out list))
                //{
                //    list = _provider.GetAllSeatRole();
                //    CacheHelper.Insert(ALlRoleCacheKey, list, CacheTime);
                //}
                //return list;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. GetAllSeatRole() ", e);
                return null;
            }
        }

        public bool CreateSeatRole(SeatRole seatRole)
        {
            try
            {
                if (_provider.CreateSeatRole(seatRole))
                {
                    CacheHelper.Remove(ALlRoleCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. CreateSeatRole() ", e);
                return false;
            }
        }

        public bool UpdateSeatRole(SeatRole seatRole)
        {
            try
            {
                if (_provider.UpdateSeatRole(seatRole))
                {
                    CacheHelper.Remove(ALlRoleCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. UpdateSeatRole() ", e);
                return false;
            }
        }
        public bool DeleteSeatRole(Guid roleID)
        {
            try
            {
                if (_provider.DeleteSeatRole(roleID))
                {
                    CacheHelper.Remove(ALlRoleCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. DeleteSeatRole() ", e);
                return false;
            }
        }

        public bool CreateSeatUser(SeatUser seatUser)
        {
            try
            {
                if (_provider.CreateSeatUser(seatUser))
                {
                    CacheHelper.Remove(ALlUserCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. CreateSeatUser() ", e);
                return false;
            }
        }
        public Model.Enums.DataAccessReturnValue ChangePassword(SeatUser seatUser, byte[] oldPassword)
        {
            try
            {
                return _provider.ChangePassword(seatUser, oldPassword);
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. ChangePassword() ", e);
                return Model.Enums.DataAccessReturnValue.更新失败;
            }
        }
        public bool UpdateSeatUser(SeatUser seatUser)
        {
            try
            {
                if (_provider.UpdateSeatUser(seatUser))
                {
                    CacheHelper.Remove(ALlUserCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. UpdateSeatUser() ", e);
                return false;
            }
        }
        public bool DeleteSeatUser(Guid userID, bool deleteFlag)
        {
            try
            {
                if (_provider.DeleteSeatUser(userID, deleteFlag))
                {
                    CacheHelper.Remove(ALlUserCacheKey);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. DeleteSeatUser() ", e);
                return false;
            }
        }

        public List<SeatUser> GetAllSeatUser(int flag)
        {
            try
            {
                List<SeatUser> list = CacheHelper.Get<List<SeatUser>>(ALlUserCacheKey);

                if (list == null)
                {
                    list = _provider.GetAllSeatUser(0);
                    System.Web.Caching.SqlCacheDependency dependency = new System.Web.Caching.SqlCacheDependency
                       (System.Configuration.ConfigurationManager.AppSettings["CurrentDB"], "SeatUser");

                    CacheHelper.Insert(ALlUserCacheKey , list, dependency);
                }

                if (flag == 0)
                {
                    return list;
                }
                else
                {
                    return list.Where(f => f.DeleteFlag = true).ToList();
                }
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. GetAllSeatUser() ", e);
                return null;
            }
        }
        public bool CreateSeat(Seat seat)
        {
            try
            {
                if (_provider.CreateSeat(seat))
                {
                    CacheHelper.Remove(ALlSeatCacheKey);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. CreateSeat() ", e);
                return false;
            }
        }

        public bool DeleteSeat(Seat seat)
        {
            try
            {
                if (_provider.DeleteSeat(seat))
                {
                    CacheHelper.Remove(ALlSeatCacheKey);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. DeleteSeat() ", e);
                return false;
            }
        }

        public bool UpdateSeat(Seat seat)
        {
            try
            {
                if (_provider.UpdateSeat(seat))
                {
                    CacheHelper.Remove(ALlSeatCacheKey);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. UpdateSeat() ", e);
                return false;
            }
        }

        public List<Seat> GetAllSeat()
        {
            try
            {
                List<Seat> list;
                if (!CacheHelper.TryGet<List<Seat>>(ALlSeatCacheKey, out list))
                {
                    list = _provider.GetModelList<Seat>("up_GetAllSeat");

                    System.Web.Caching.SqlCacheDependency dependency = new System.Web.Caching.SqlCacheDependency
                        (System.Configuration.ConfigurationManager.AppSettings["CurrentDB"], "Seat");

                    CacheHelper.Insert(ALlSeatCacheKey, list, dependency);
                }
                return list;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. GetAllSeat() ", e);
                return null;
            }
        }

        public List<SystemModule> GetSystemModules()
        {
            try
            {
                List<SystemModule> list;
                //CacheHelper.Remove(ALlSystemModuleCacheKey);
                if (!CacheHelper.TryGet<List<SystemModule>>(ALlSystemModuleCacheKey, out list))
                {
                    list = _provider.GetSystemModules();

                    System.Web.Caching.SqlCacheDependency dependency = new System.Web.Caching.SqlCacheDependency
                      (System.Configuration.ConfigurationManager.AppSettings["CurrentDB"], "Seat");

                    CacheHelper.Insert(ALlSystemModuleCacheKey, list, dependency);

                    //CacheHelper.Insert(ALlSystemModuleCacheKey, list, CacheTime);
                }
                return list;
            }
            catch (Exception e)
            {
                Logger.Error("AuthManager. GetSystemModules() ", e);
                return null;
            }
        }

        #endregion

        #region User Auth Methods

        public SeatUser Login(string userName, byte[] password, Guid seatId)
        {
            try
            {
                return _provider.Login(userName, password, seatId);
            }
            catch (Exception e)
            {
                Logger.Error("Error login: " + userName, e);
                return null;
            }
        }

        public bool Logout(Guid userId, Guid seatId)
        {
            try
            {
                return _provider.Logout(userId, seatId);
            }
            catch (Exception e)
            {
                Logger.Error("Error logout: " + userId.ToString() + " Seat:" + seatId.ToString(), e);
                return false;
            }
        }

        public Seat GetSeatByMac(string mac)
        {
            return GetAllSeat().Find(s => s.MAC == mac);
        }

        public SeatRole GetRoleByID(Guid RoleId)
        {
            return GetAllSeatRole().Find(r => r.RoleID == RoleId);
        }

        public List<SeatTails> GetAllSeatTails()
        {
            List<SeatTails> result = null;
            try
            {
                result = _provider.GetAllSeatTails();
            }
            catch (Exception e)
            {
                Logger.Error("error in get All Seat Tails ", e);

                result = new List<SeatTails>();
            }
            return result;
        }

        public List<PlaneType> GetAllPlaneType()
        {
            List<PlaneType> result = null;
            try
            {
                result = _provider.GetAllPlaneType();
            }
            catch (Exception e)
            {
                Logger.Error(" error in get all PlaneType", e);

                result = new List<PlaneType>();
            }
            return result;
        }

        public string SaveSeatTails(Guid SeatID, string[] Tails)
        {
            return _provider.SaveSeatTails(SeatID, Tails);
        }

        public bool SeatUserIsLogin(Guid SeatID, string UserName)
        {
            bool result = false;
            try
            {
                result = _provider.SeatUserIsLogin(SeatID, UserName);
            }
            catch(Exception e)
            {
                Logger.Error(e);
                result = false;
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<PlaneType> GetAllTailAndType()
        {
            List<PlaneType> typeList = GetAllPlaneType();

            foreach (PlaneType type in typeList)
            {
                try
                {
                    type.TailList = CommonCacheData.CacheACARDevice.GetTailsByPlaneType(type.PlaneTypeID);
                }
                catch (Exception e)
                {
                    Logger.Error("error in get all TailAndType,TypeID:"+type.PlaneTypeID.ToString(), e);
                }
            }


            return typeList;
        }

        public string InsertPlaneType(PlaneType model)
        {
            string result = "";
            try
            {
                result = _provider.InsertPlaneType(model);
            }
            catch (Exception e)
            {
                Logger.Error(e);
                result = "插入数据发生错误";
            }

            return result;
        }


        public string UpdatePlaneType(PlaneType model)
        {
            string result = "";
            try
            {
                result = _provider.UpdatePlaneType(model);
            }
            catch (Exception e)
            {
                Logger.Error(e);
                result = "更新数据发生错误";
            }

            return result;
        }

        public string InsertPlaneInfo(ACARSDevice model)
        {
            string result = "";
            try
            {
                result = _provider.InsertPlaneInfo(model);
            }
            catch (Exception e)
            {
                Logger.Error(e);
                result = "插入数据发生错误";
            }

            return result;
        }

        public string UpdatePlaneInfo(ACARSDevice model)
        {
            string result = "";
            try
            {
                result = _provider.UpdatePlaneInfo(model);
            }
            catch (Exception e)
            {
                Logger.Error(e);
                result = "更新数据发生错误";
            }

            return result;
        }

        public bool DeletePlaneType(int TypeID, string ParentOrChild)
        {
            return _provider.DeletePlaneType(TypeID,ParentOrChild);
        }

        public bool DeletePlaneInfo(string tailNo)
        {
            return _provider.DeletePlaneInfo(tailNo);
        }

        public List<Seat> GetDelegatableSeats(Guid SeatID)
        {
            return _provider.GetDelegatableSeats(SeatID);
        }

        public string InsertDelegateRelation(SeatRelation Model)
        {
            string result = "";
            try
            {
                result=_provider.InsertDelegateRelation(Model);
            }
            catch (Exception e)
            {
                Logger.Error("error in insert SeatRelation,SeatID:"+Model.SelfSeatID.ToString(),e);
                result = "插入数据失败";
            }

            return result;
        }

        public string UpdateDelegateStatus(Guid RelationID, int Status)
        {
            string result = "";

            try
            {
                _provider.UpdateDelegateStatus(RelationID, Status);
            }
            catch (Exception e)
            {
                Logger.Error("error in Update delegate status,RelationID:"+RelationID.ToString(),e);
                result = "更新数据失败";
            }
            return result;
        }

        #endregion
    }
}
